<?php

/**
 * @author 陈韵
 * 贵阳仓保税自提业务
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssLogModel\MessageCallBackNotifyLog;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\Shopguiyang\ShopguiyangApiClient;
use App\Service\TaskServer\TaskWorker;
use App\Service\OrderService\OrderNotifyService\GwNotifyService;

class Shopguiyang extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //生成供应商主单号
        $supplierGoodsInfo      = $param['supplierGoodsInfo'];
        $supplierCode           = $supplierGoodsInfo['supplierCode'];
        $apiBody                = $supplierGoodsInfo['apiBody'];
        $thirdPartyPlatformCode = $supplierGoodsInfo['thirdPartyPlatformCode'];
        //下单商品组
        $userGoodsList          = $supplierGoodsInfo['userGoodsList'];
        //下单商品
        $orderGoods = [];
        foreach ($userGoodsList as $item ) {
            $orderGoods = array_merge($orderGoods,$item);
            unset($item);
        }
        
        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;
    
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;
        
        //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
        if( $isDelare && !$isShop ) {
            $param['order']['supplier_dsn'] = (string)$param['order']['orderSn'];
        } else {
            $param['order']['supplier_dsn'] = (string)(IdService::instance()->getOtherID());
        }
        $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
        $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
        $param['order']['goods'] = $orderGoods;
        $param['order']['isQueryExpress'] = 1;//查询物流单
        $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $orderItems[] = $res['data'];
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }
    
    /**
     * 订单申报
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        return $this->callSdkApi(ShopguiyangApiClient::class,$param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return $this->callSdkApi(ShopguiyangApiClient::class,$param['apiBody'])->cancelOrder($param);
    }
    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }
        
        //向你他云查询订单放行状态
        $result_api = $this->callSdkApi(ShopguiyangApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if( $result_api['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        
        if( empty($result_api['data']) ) {
            return Normal::returnCode(Normal::FAIL,"未查到报关信息");
        }
        $contents       = current($result_api['data']['Result']);
        $statusData     = $this->getUpstreamOrderStatusMap($contents);
        $order_sn       = $orderInfo['order_sn'];
        $orderStatus    = $statusData['orderStatus'];
        $contents       = array_merge($contents,$statusData);
        $messageData    = MessageCallBackNotifyLog::instance()->info(['event_sn'=>$order_sn,'declare_status'=>$orderStatus]);
        if( empty($messageData) ) {
            MessageCallBackNotifyLog::instance()->add([
                'event_sn'      => $order_sn,
                'user_type'     => 'shopguiyang',
                'message_type'  => 'OrderExpress',
                'status'        => 0,
                'message'       => json_encode($contents,JSON_UNESCAPED_UNICODE),
                'declare_status'=> $orderStatus,
                'source'        => 2,
                'request_ip'    => '127.0.0.1',
                'cd'            => time(),
            ]);
        }
        
        return Normal::returnCode(Normal::SUC,"写入完成",[
            'is_need_send_express'  => 1
        ]);
    }
    
    /**
     * 获取上游状态处理为下下游标准状态
     * @param unknown $orderStatus
     */
    public function getUpstreamOrderStatusMap( array $contents )
    {
        $ManifestDeclareStatusValue = (int)$contents['ManifestDeclareStatusValue'];
        $ManifestDeclareStatusName  = $contents['ManifestDeclareStatusName'];
        $OrderStatus = $contents['OrderStatus'];
        if( !in_array($OrderStatus,["-1","-2"]) ) 
        {
            if( $ManifestDeclareStatusValue == 800 )//放行
            {
                return [
                    'orderStatus'       => 2,
                    'orderStatusName'   => $this->orderStatus[2]
                ];
            }
            elseif ( in_array($ManifestDeclareStatusValue,['-5','-4','-3','-1','4','100','-1','300','399','500','501','502','503','599','700']))
            {
                //-1-处理异常-5:已撤销,-4:撤销中,-3:作废,发送海关失败
                //-5:已撤销,-4:撤销中,-3:作废,扣留移送通关\扣留移送法规\扣留移送缉私\退运
                return [
                    'orderStatus'       => 4,
                    'orderStatusName'   => $this->orderStatus[4]
                ];
            }
            elseif ( in_array($ManifestDeclareStatusValue,['0','1','2','3','120','899']))//\电子口岸已暂存\电子口岸申报中\发送海关成功\海关入库\人工审核\海关审结
            {
                return [
                    'orderStatus'       => 1,
                    'orderStatusName'   => $this->orderStatus[1]
                ];
            }
            else 
            {
                return [
                    'orderStatus'       => 4,
                    'orderStatusName'   => $this->orderStatus[4]
                ];
            }
        } else {
            return [
                'orderStatus'       => 3,
                'orderStatusName'   => $this->orderStatus[3]
            ];
        }
    }

     /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList( $param = [] )
    {
        $res = $this->callSdkApi(ShopguiyangApiClient::class,$param['apiBody'])->queryGoodsListBySkuNo($param['queryBody']);
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total'     => count($res) ?? 0,
            'list'      => $res,
            'hasPage'   => false//是否支持分页功能
        ]);
    }
    
}